package com.katze.common.ws.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.katze.common.ws.protocol.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.EncoderException;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus;

import java.util.List;

public class MessageDecoderHandler extends MessageToMessageCodec<TextWebSocketFrame, Message> {
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    protected void decode(ChannelHandlerContext ctx, TextWebSocketFrame frame, List<Object> out) throws Exception {
        try {
            Message message = mapper.readValue(frame.text(), Message.class);
            out.add(message);
        } catch (JsonProcessingException e) {
            ctx.fireExceptionCaught(new DecoderException("JSON 解析失败", e));
        }
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Message message, List<Object> out) throws Exception {
        try {
            if (message.getCode() == 401) {
                out.add(new CloseWebSocketFrame(WebSocketCloseStatus.valueOf(message.getCode() * 10), (String) message.getData()));
            } else {
                String json = mapper.writeValueAsString(message);
                out.add(new TextWebSocketFrame(json));
            }
        } catch (JsonProcessingException e) {
            ctx.fireExceptionCaught(new EncoderException("JSON序列化失败", e));
        }
    }
}
